package org.hentai.bt.util.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlMap {

    public static Map<String, List<String>> analyseXmlDocument(Document document) {

        Map<String, List<String>> sqlTables = new HashMap<>();

        Element rootElement = document.getRootElement();
        for (Object element : rootElement.elements()) {
            Element ele = (Element) element;

            List<String> sqlElements = new ArrayList<>();

            for (Object el : ele.elements()) {
                Element e = (Element) el;
                StringBuffer tableField = new StringBuffer();

                xmlDocumentIterator(e, tableField);
                sqlElements.add(tableField.toString());

            }

            // 主键
            String primaryKey = ele.element("primaryKey").getText();
            sqlElements.add(String.format("PRIMARY KEY %s", primaryKey));
            sqlElements.add(ele.element("foreignKey").getText());

            sqlTables.put(ele.attribute("table").getValue(), sqlElements);
        }

        return sqlTables;
    }

    private static void xmlDocumentIterator(Element root, StringBuffer sql) {

        switch (root.getName()) {
            case "field":
                String name = root.attributeValue("name");
                sql.append(" ").append(name);
                break;

            case "element":
                String element = root.attributeValue("name");
                if (element.equals("VARCHAR")) {
                    sql.append(" ").append(element).append("(&#-maxlength-#&)");
                } else {
                    sql.append(" ").append(element);
                }
                break;

            case "isNull":
                String isNull = root.attributeValue("if");
                if (isNull.equals("false")) {
                    sql.append(" NULL");
                } else if (isNull.equals("true")) {
                    sql.append(" NOT NULL");
                }
                break;

            case "remark":
                for (Object attribute : root.attributes()) {
                    Attribute attr = (Attribute) attribute;
                    if (attr.getName().equals("maxlength")) {
                        String replace = sql.toString().replace("&#-maxlength-#&", attr.getValue());
                        sql.delete(0, sql.length()).append(replace);
                    } else {
                        sql.append(" ").append(attr.getValue());
                    }
                }
        }

        for (Object element : root.elements()) {
            xmlDocumentIterator((Element) element, sql);
        }

    }

}
